package com.masterclient.app.modules.goods.adapter;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.eoner.baselibrary.bean.goods.CommodityDetailData;
import com.eoner.baselibrary.bean.goods.VipUpgradeBean;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.eoner.commonbean.product.CommodityOversea;
import com.eoner.commonbean.product.ProductTag;
import com.eoner.managerlibrary.user.UserDataManager;
import com.masterclient.app.R;
import com.masterclient.app.base.MainViewHolder;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.masterclient.app.widget.PriceIntegralLayout;
import com.masterclient.app.widget.TagTextView;
import com.masterclient.app.widget.UpgradeVipLayout;

import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.glide.transformations.CropCircleWithBorderTransformation;

public class CommodityDetailInformationAdapter extends DelegateAdapter.Adapter<MainViewHolder> {

    Activity mContext;

    private LayoutHelper mLayoutHelper;


    private VirtualLayoutManager.LayoutParams mLayoutParams;
    private int mCount = 0;
    private boolean isShowCollect = true;

    CommodityDetailData data;

    public interface OnInformationCallback{
        void favoriteClick();
        void upgradeClick();
    }

    OnInformationCallback onInformationCallback;

    public OnInformationCallback getOnInformationCallback() {
        return onInformationCallback;
    }

    public void setOnInformationCallback(OnInformationCallback onInformationCallback) {
        this.onInformationCallback = onInformationCallback;
    }

    public CommodityDetailInformationAdapter(Activity context, LayoutHelper layoutHelper, int count) {
        this(context, layoutHelper, count, null,null,true);
    }

    public CommodityDetailInformationAdapter(Activity context, LayoutHelper layoutHelper, int count,
                                             @NonNull VirtualLayoutManager.LayoutParams layoutParams, CommodityDetailData data,boolean isShowCollect) {
        this.mContext = context;
        this.mLayoutHelper = layoutHelper;
        this.mCount = count;
        this.mLayoutParams = layoutParams;
        this.data = data;
        this.isShowCollect = isShowCollect;
    }
    @Override
    public LayoutHelper onCreateLayoutHelper() {
        return mLayoutHelper;
    }
    @Override
    protected void onBindViewHolderWithOffset(MainViewHolder holder, int position, int offsetTotal) {

    }

    private int spec;
    private int popupWidth;
    private int popupHeight;
    private String mCopiedText;

    @Override
    public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return null;
    }
    @Override
    public void onBindViewHolder(MainViewHolder holder, int position) {
        if(mLayoutParams!=null) {
            holder.itemView.setLayoutParams(
                    new VirtualLayoutManager.LayoutParams(mLayoutParams));
        }

        LinearLayout detailPriceLayout = holder.itemView.findViewById(R.id.detail_price_layout);
        TextView tvActivityTag = holder.itemView.findViewById(R.id.tv_activity_tag);
        TextView tvDayTxt = holder.itemView.findViewById(R.id.tv_day_txt);
        TextView tvDayPrice = holder.itemView.findViewById(R.id.tv_day_price);
        TextView tvOfficialTxt = holder.itemView.findViewById(R.id.tv_official_txt);
        TextView tvOfficialPrice = holder.itemView.findViewById(R.id.tv_official_price);
        TextView tvCommissionTxt = holder.itemView.findViewById(R.id.tv_commission_txt);
        TextView tvCoinTxt = holder.itemView.findViewById(R.id.tv_coin_txt);
        TextView tvBuyActivityTxt = holder.itemView.findViewById(R.id.tv_buy_activity_txt);
        TextView tvAwardActivityTxt = holder.itemView.findViewById(R.id.tv_award_activity_txt);
        holder.itemView.findViewById(R.id.product_details_gold_layout).setVisibility(
                "2".equals(data.getProduct_type())?View.VISIBLE:View.GONE);
        detailPriceLayout.setVisibility("2".equals(data.getProduct_type())?View.GONE:View.VISIBLE);

        if (Integer.parseInt(data.getActivity_type()) == 3) {
            Utils.setDin(tvActivityTag, mContext);
            tvActivityTag.setText("赠送价");
            tvActivityTag.setVisibility(View.VISIBLE);
        } else {
            //活动文案
            if (data.getPriceTagBean() != null && !TextUtils.isEmpty(data.getPriceTagBean().getActivity_price_tag())){
                tvActivityTag.setText(data.getPriceTagBean().getActivity_price_tag());
                tvActivityTag.setVisibility(View.VISIBLE);
            }else {
                tvActivityTag.setVisibility(View.GONE);
            }
        }

        //日常价
        if (data.getPriceTagBean() != null && !TextUtils.isEmpty(data.getPriceTagBean().getBase_price_tag())){
            tvDayTxt.setText(data.getPriceTagBean().getBase_price_tag());
            if (!TextUtils.isEmpty(data.getDaily_price())){
                tvDayPrice.setText("¥" + data.getDaily_price());
                tvDayPrice.setVisibility(View.VISIBLE);
            }
            tvDayTxt.setVisibility(View.VISIBLE);
        }else {
            tvDayTxt.setVisibility(View.GONE);
            tvDayPrice.setVisibility(View.GONE);
        }

        //官方价
        if (!"2".equals(data.getProduct_type())&&data.getPriceTagBean() != null && !TextUtils.isEmpty(data.getPriceTagBean().getMarket_price_tag())){
            tvOfficialTxt.setText(data.getPriceTagBean().getMarket_price_tag());
            if (!TextUtils.isEmpty(data.getMarket_price())){
                tvOfficialPrice.setText("¥" +data.getMarket_price());
                tvOfficialPrice.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);
                tvOfficialPrice.setVisibility(View.VISIBLE);
            }
            tvOfficialTxt.setVisibility(View.VISIBLE);
        }else {
            tvOfficialTxt.setVisibility(View.GONE);
            tvOfficialPrice.setVisibility(View.GONE);
        }

        //会员价
        LinearLayout llPriceVip = holder.itemView.findViewById(R.id.layout_vip_price);
        if (data.isShow_vip_price()){
            llPriceVip.setVisibility(View.VISIBLE);
            ((TextView)holder.itemView.findViewById(R.id.tv_vip_price)).setText("¥"+data.getVip_price());
        }else {
            llPriceVip.setVisibility(View.GONE);
        }

        //新会员佣金翻倍
        if (data.getPriceTagBean() != null && !TextUtils.isEmpty(data.getPriceTagBean().getDouble_commission_tag())){
            tvCommissionTxt.setText(data.getPriceTagBean().getDouble_commission_tag());
            tvCommissionTxt.setVisibility(View.VISIBLE);
        }else {
            tvCommissionTxt.setVisibility(View.GONE);
        }

        //佣金抵扣
        if (data.getPriceTagBean() != null && !TextUtils.isEmpty(data.getPriceTagBean().getDeduction_rate_tag())){
            tvCoinTxt.setText(data.getPriceTagBean().getDeduction_rate_tag());
            tvCoinTxt.setVisibility(View.VISIBLE);
        }else {
            tvCoinTxt.setVisibility(View.GONE);
        }

        //价格行
        PriceIntegralLayout ll_price = holder.itemView.findViewById(R.id.ll_price);
        TextView tv_money_earn = holder.itemView.findViewById(R.id.tv_money_earn);
        ll_price.setData(data.getIntegral_price(), data.getPrice());
        ll_price.floadSize(0.655f);
//        if (!TextUtils.isEmpty(data.getLine_price())&&Float.parseFloat(data.getLine_price())!=0&&
//                Float.parseFloat(data.getLine_price()) != Float.parseFloat(data.getPrice())) {
//            line_price.setText("¥" + data.getLine_price());
//            line_price.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
//        }
        String product_type = data.getProduct_type();
        if ("4".equals(product_type) || "3".equals(product_type)
                || "2".equals(product_type) || TextUtils.isEmpty(data.getCommission()) || 0 == Double.valueOf(data.getCommission())) {
            tv_money_earn.setVisibility(View.GONE);
        } else {
            tv_money_earn.setText("赚" + data.getCommission());
            tv_money_earn.setVisibility(View.VISIBLE);
        }

        List<ProductTag> tags =  data.getTags();
        String new_member_tag = "";//新人标签
        String buy_activity_tag = "";//购物消费活动商品Tag
        String award_activityTxt_tag = "";//开单奖励活动商品Tag
        for (ProductTag tag :  tags){
            if("2".equals(tag.getType())){
                new_member_tag = tag.getName();
            }else if ("7".equals(tag.getType())){
                buy_activity_tag = tag.getName();
            }else if ("6".equals(tag.getType())){
                award_activityTxt_tag = tag.getName();
            }
        }

        //购物消费活动商品Tag
        if (!TextUtils.isEmpty(buy_activity_tag)){
            tvBuyActivityTxt.setText(buy_activity_tag);
            tvBuyActivityTxt.setVisibility(View.VISIBLE);
        }else {
            tvBuyActivityTxt.setVisibility(View.GONE);
        }

        //开单奖励活动商品Tag
        if (!TextUtils.isEmpty(award_activityTxt_tag)){
            tvAwardActivityTxt.setText(award_activityTxt_tag);
            tvAwardActivityTxt.setVisibility(View.VISIBLE);
        }else {
            tvAwardActivityTxt.setVisibility(View.GONE);
        }

        //券后价
        float coupon_price_amount = Float.valueOf(data.getAfter_coupon_price());
        TextView coupon_price = holder.itemView.findViewById(R.id.coupon_price);
        TextView coupon_price_flag = holder.itemView.findViewById(R.id.coupon_price_flag);
        View coupon_price_layout = holder.itemView.findViewById(R.id.coupon_price_layout);
        if(coupon_price_amount < 0){
            coupon_price_layout.setVisibility(View.GONE);
        }else{
            coupon_price_layout.setVisibility(View.VISIBLE);
            coupon_price.setText("¥" + data.getAfter_coupon_price());
            if(data.isIs_same_coupon_price()){
                coupon_price_flag.setVisibility(View.GONE);
            }else {
                coupon_price_flag.setVisibility(View.VISIBLE);
            }
        }


        //试用领取
        TextView tv_goods_limit = holder.itemView.findViewById(R.id.tv_goods_limit);
        if ("3".equals(product_type)) {
            tv_goods_limit.setVisibility(View.VISIBLE);
            tv_goods_limit.setText("销量 " + data.getSold_num_desc());
        }else {
            if(TextUtils.isEmpty(data.getSold_num_desc())||"0".equals(data.getSold_num_desc())){
                tv_goods_limit.setVisibility(View.GONE);
            }else {
                tv_goods_limit.setVisibility(View.VISIBLE);
                tv_goods_limit.setText("销量 " + data.getSold_num_desc());
            }
        }
        //佣金翻倍
//        View ll_money_earn_double = holder.itemView.findViewById(R.id.ll_money_earn_double);
//        TextView tv_money_earn_double = holder.itemView.findViewById(R.id.tv_money_earn_double);
//        TextView tv_money_earn_doubleline = holder.itemView.findViewById(R.id.tv_money_earn_doubleline);
//        if(!TextUtils.isEmpty(data.getDouble_commission()) && Float.valueOf(data.getDouble_commission()) > 0){
//            tv_money_earn_double.setText("赚" + data.getDouble_commission());
//            tv_money_earn_doubleline.setText("赚" + data.getCommission());
//            tv_money_earn_doubleline.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
//            tv_money_earn.setVisibility(View.GONE);
//            ll_money_earn_double.setVisibility(View.VISIBLE);
//        }else{
//            ll_money_earn_double.setVisibility(View.GONE);
//        }
        //升级提醒
        UpgradeVipLayout goods_detail_vip = holder.itemView.findViewById(R.id.goods_detail_vip);
//        ImageView goods_detail_vip_icon = holder.itemView.findViewById(R.id.goods_detail_vip_icon);
//        TextView goods_detail_vip_text = holder.itemView.findViewById(R.id.goods_detail_vip_text);
//        TextView goods_detail_vip_btn = holder.itemView.findViewById(R.id.goods_detail_vip_btn);
        VipUpgradeBean upgrade = data.getUpgrade_to_vip();
        if(upgrade == null | (upgrade != null && TextUtils.isEmpty(upgrade.getMessage())) |
                Integer.valueOf(UserDataManager.getInstance().getRoleLevel()) > 0 | !isShowCollect){
            goods_detail_vip.setVisibility(View.GONE);
        }else{
            goods_detail_vip.setVisibility(View.VISIBLE);
            goods_detail_vip.setData(upgrade,false,"商品详情");
            goods_detail_vip.setUpgradeVipClick(new UpgradeVipLayout.UpgradeVipClick() {
                @Override
                public void onUpgradeVip(String upgradeVipUrl) {
                    if ("4".equals(product_type)){
                        //buyNow();购买按钮
                        if(onInformationCallback != null){
                            onInformationCallback.upgradeClick();
                        }
                    }else {
                        Intent intent = new Intent(mContext,BridgeActivity.class);
                        intent.putExtra("url", upgradeVipUrl);
                        mContext.startActivity(intent);
                    }
                }
            });

        }

        //海外购--标题相关显示
        CommodityOversea oversea = data.getOversea();
        View ll_country = holder.itemView.findViewById(R.id.ll_country);
        ImageView iv_country_tag = holder.itemView.findViewById(R.id.iv_country_tag);
        TextView tv_country_des = holder.itemView.findViewById(R.id.tv_country_des);

        TagTextView tv_goods_name = holder.itemView.findViewById(R.id.tv_goods_name);
        if(oversea == null | (oversea != null && TextUtils.isEmpty(oversea.getCountry_name()))){
            ll_country.setVisibility(View.GONE);
        }else{
            ll_country.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(oversea.getCountry_logo())){
                iv_country_tag.setVisibility(View.VISIBLE);
                ViewTransformUtil.glideImageView(mContext,oversea.getCountry_logo(),iv_country_tag,
                        new CropCircleWithBorderTransformation(0,0x0A3D2529),0);
            }else {
                iv_country_tag.setVisibility(View.GONE);
            }
            tv_country_des.setText(oversea.getCountry_name() + "  " + oversea.getDesc());
        }

//        if (oversea != null && !TextUtils.isEmpty(oversea.getCountry_name())){
//            List<String> tagList = new ArrayList<>();
//            tagList.add(oversea.getTag());
//            tv_goods_name.setContentAndTag(" " + data.getTitle(), tagList,R.layout.view_good_detail_tag);
//        }else {
//            tv_goods_name.setText(data.getTitle());
//        }

//        tv_goods_name.setContentCommodityDetails(" "+ data.getTitle(),oversea != null &&
//                !TextUtils.isEmpty(oversea.getCountry_name())?oversea.getTag():"","VIP专享");

            List<String> tagList = new ArrayList<>();
        if (oversea != null && !TextUtils.isEmpty(oversea.getCountry_name())) {
            tagList.add(oversea.getTag());
        }

        boolean isVipExclusive = !TextUtils.isEmpty(data.getIntegral_product_vip_exclusive())&&"1".equals(data.getIntegral_product_vip_exclusive());
        tv_goods_name.setContentAndTag((tagList.size()>0&&isVipExclusive?" ":"") + data.getTitle(), tagList,R.layout.view_good_detail_tag, isVipExclusive);

        initPopupWindow();

        TextView sub_title_txt = holder.itemView.findViewById(R.id.sub_title_txt);
        if(TextUtils.isEmpty(data.getSub_title())){
            sub_title_txt.setVisibility(View.GONE);
        }else{
            sub_title_txt.setVisibility(View.VISIBLE);
            sub_title_txt.setText(data.getSub_title());
        }

        tv_goods_name.setOnLongClickListener(view -> {
            spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            tv_goods_name.measure(spec, spec);
            popupHeight = tv_goods_name.getMeasuredHeight();
            popupWidth = tv_goods_name.getMeasuredWidth();

            showUp(tv_goods_name);
            mCopiedText = ((TextView) view).getText().toString();
            return false;
        });

        //收藏按钮
        ImageView gzg_collect_icon = holder.itemView.findViewById(R.id.gzg_collect_icon);
        if (isShowCollect){
            gzg_collect_icon.setVisibility(View.VISIBLE);
            if (!data.isIs_favorite()) {
                gzg_collect_icon.setImageResource(R.mipmap.gzg_collect_icon);
            } else {
                gzg_collect_icon.setImageResource(R.mipmap.gzg_collected_icon);
            }
            if (data.isShow_favorite_button()) {
                gzg_collect_icon.setVisibility(View.VISIBLE);
            } else {
                gzg_collect_icon.setVisibility(View.GONE);
            }
            gzg_collect_icon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(onInformationCallback != null){
                        onInformationCallback.favoriteClick();
                    }
                }
            });
        }else {
            gzg_collect_icon.setVisibility(View.GONE);
        }
    }

    private PopupWindow mPopupWindow;
    private void initPopupWindow() {
        View popupView = mContext.getLayoutInflater().inflate(R.layout.popup_text_copy, null);

        mPopupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable(mContext.getResources(), (Bitmap) null));

        TextView tvCopy = popupView.findViewById(R.id.tv_copy);
        tvCopy.setOnClickListener(view -> {
            copyText(mCopiedText);
            if (mPopupWindow != null && mPopupWindow.isShowing()) {
                mPopupWindow.dismiss();
            }
        });
    }

    private void copyText(String copiedText) {
        ClipboardManager clipboardManager = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
        clipboardManager.setPrimaryClip(ClipData.newPlainText(null, copiedText));
        Toast.makeText(mContext,"复制标题成功",Toast.LENGTH_LONG).show();
    }

    private void showUp(View v) {
        //获取需要在其上方显示的控件的位置信息
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        //在控件上方显示
        mPopupWindow.showAtLocation(v, Gravity.NO_GRAVITY,  popupWidth / 2, location[1] - popupHeight-40);
    }


    @Override
    public int getItemCount() {
        return mCount;
    }

    @Override
    public int getItemViewType(int position) {
        return 2;
    }
}
